package com.wish233.wrpcspringbootstarter.boostrap;

import com.wish233.proxy.ServiceProxyFactory;
import com.wish233.wrpcspringbootstarter.annotation.WrpcReference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * @author WHH
 */
public class RpcConsumerBootStrap implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            WrpcReference wrpcReference = field.getAnnotation(WrpcReference.class);
            if (wrpcReference != null) {
                //为他注入代理对象
                Class<?> referenceClass = wrpcReference.referenceClass();
                if (referenceClass == void.class) {
                    referenceClass = field.getType();
                }
                field.setAccessible(true);
                Object proxy = ServiceProxyFactory.getProxy(referenceClass);
                try {
                    field.set(bean, proxy);
                    field.setAccessible(false);
                } catch (Exception e) {
                    throw new RuntimeException("为" + beanName + "注入字段" + field.getName() + "失败", e);
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
